package com.zzyl.framework.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import lombok.SneakyThrows;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 修改MP自动填充拦截器
     * 由于小程序端的所有请求不走后台的用户，在新增或修改的时候，不需要自动填充创建人和修改人
     *
     */
    @Autowired
    private HttpServletRequest httpServletRequest;

    @SneakyThrows // 忽略异常
    public boolean isExclude() {
        try {
            String requestURI = httpServletRequest.getRequestURI();
            if(requestURI.startsWith("/member")){
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    // 插入数据时自动填充
    @Override
    public void insertFill(MetaObject metaObject) {
        // this.strictInsertFill(metaObject, "createBy", String.class, String.valueOf(getLoginUserId()));
        this.strictInsertFill(metaObject, "createTime", Date.class, DateUtils.getNowDate());
        if (!isExclude()) {
            this.strictInsertFill(metaObject, "createBy", String.class, loadUserId() + "");
        }
    }

    // 修改数据时自动填充
    @Override
    public void updateFill(MetaObject metaObject) {
        // this.setFieldValByName("updateBy", String.valueOf(getLoginUserId()), metaObject);
        this.setFieldValByName("updateTime", DateUtils.getNowDate(), metaObject);
//        this.strictUpdateFill(metaObject, "updateBy", String.class, String.valueOf(getLoginUserId()));
//        this.strictUpdateFill(metaObject, "updateTime", Date.class, DateUtils.getNowDate());
        if (!isExclude()) {
            this.setFieldValByName("updateBy", loadUserId() + "", metaObject);
        }
    }

    // 获取当前登录人的id
   /* public Long getLoginUserId() {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (ObjectUtils.isNotEmpty(loginUser)) {
                return loginUser.getUserId();
            }
            return 1L;
        } catch (Exception e) {
            return 1L;
        }
    }*/
    private static Long loadUserId() {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (ObjectUtil.isNotEmpty(loginUser)) {
                return loginUser.getUserId();
            }
            return 1L;
        } catch (Exception e) {
            return 1L;
        }
    }

}
